<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { computed, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './account.data';
  import { registeraccount, setrole, resetpassword } from '/@/api/system/role';
  const emit = defineEmits(['success', 'register']);

  let type = ref('add');
  let info = {} as any;
  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    updateSchema([
      {
        field: 'Name',
        ifShow: true,
      },
      {
        field: 'Password',
        ifShow: true,
      },
      {
        field: 'ConfirmPassword',
        ifShow: true,
      },
      {
        field: 'UserName',
        ifShow: true,
      },
      {
        field: 'Role',
        ifShow: true,
      },
    ]);
    resetFields();
    setModalProps({ confirmLoading: false });
    type.value = data?.type || 'add';
    info = data.record || {};
    if (type.value === 'role') {
      setFieldsValue({
        Role: info.RoleName,
      });
      updateSchema([
        {
          field: 'Name',
          ifShow: false,
        },
        {
          field: 'Password',
          ifShow: false,
        },
        {
          field: 'ConfirmPassword',
          ifShow: false,
        },
        {
          field: 'UserName',
          ifShow: false,
        },
      ]);
    } else if (type.value === 'password') {
      updateSchema([
        {
          field: 'Name',
          ifShow: false,
        },
        {
          field: 'UserName',
          ifShow: false,
        },
        {
          field: 'Role',
          ifShow: false,
        },
      ]);
    }
  });

  const getTitle = computed(() =>
    type.value === 'add' ? '新增账号' : type.value === 'role' ? '修改角色' : '修改密码',
  );

  async function handleSubmit() {
    try {
      const { Name, Role, Password, ConfirmPassword, UserName } = await validate();
      setModalProps({ confirmLoading: true });
      if (type.value === 'add') {
        await registeraccount([UserName, Name, Password, ConfirmPassword, Role]);
      } else if (type.value === 'role') {
        await setrole([info.UserName, Role]);
      } else if (type.value === 'password') {
        await resetpassword([info.UserName, Password, ConfirmPassword]);
      }
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
